<template>
    <!-- components/custom-tabbar/index.wxml -->
    <view class="tabbar">
        <view
            :class="'tabbar-item ' + (selected === index ? 'active' : '')"
            @tap="switchTab"
            :data-path="item.pagePath"
            :data-index="index"
            v-for="(item, index) in list"
            :key="index"
        >
            <image class="tabbar-icon" :src="'https://image.shengxuankj.com/fronts/' + (selected === index ? item.selectedIconPath : item.iconPath)"></image>

            <text class="tabbar-text">{{ item.text }}</text>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, defineProps } from 'vue';

// 类型定义
interface TabItem {
  pagePath: string;
  iconPath: string;
  selectedIconPath: string;
  text: string;
}

interface Props {
  selected?: number;
}

interface TouchEvent {
  currentTarget: {
    dataset: {
      path: string;
      index: number;
    };
  };
}

// Props定义
const props = withDefaults(defineProps<Props>(), {
  selected: 0
});

// 响应式数据
const list = ref<TabItem[]>([
  {
    pagePath: 'pages/index/index',
    iconPath: 'home_none.png',
    selectedIconPath: 'home_block.png',
    text: '首页'
  },
  {
    pagePath: 'pages/tales/tales',
    iconPath: 'order_none.png',
    selectedIconPath: 'order_block.png',
    text: '预定'
  },
  {
    pagePath: 'pages/profile/profile',
    iconPath: 'main_none.png',
    selectedIconPath: 'main_block.png',
    text: '我的'
  }
]);

/**
 * 切换标签页
 * @param e 触摸事件
 */
const switchTab = (e: TouchEvent): void => {
  console.log(e);
  const { path, index } = e.currentTarget.dataset;

  // 触发父组件事件
  // this.triggerEvent('tabchange', {
  //   index: index,
  //   path: path
  // });
  console.log(getCurrentPages()[getCurrentPages().length - 1]);
  // 跳转页面
  if (path !== getCurrentPages()[getCurrentPages().length - 1].route) {
    uni.reLaunch({
      url: `/${path}`
    });
  }
};

// 暴露给模板使用的变量和方法
defineExpose({
  list,
  switchTab
});
</script>
<style>
/* components/custom-tabbar/index.wxss */
.tabbar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    background-color: #ffffff;
    border-top: 1rpx solid #e5e5e5;
    display: flex;
    padding-bottom: env(safe-area-inset-bottom);
    z-index: 1000;
}

.tabbar-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 10rpx 0;
}

.tabbar-icon {
    width: 48rpx;
    height: 48rpx;
    margin-bottom: 4rpx;
}

.tabbar-text {
    font-size: 20rpx;
    color: #999999;
}

.tabbar-item.active .tabbar-text {
    color: #4caf50;
}
</style>
